package com.bwf.lgqingdan.mvp.model.impl;

import com.alibaba.fastjson.JSON;
import com.bwf.lgqingdan.entity.ResponseCategoryThing;
import com.bwf.lgqingdan.entity.ResponseThings;
import com.bwf.lgqingdan.mvp.model.CategoryThingModel;
import com.bwf.lgqingdan.utils.Apis;
import com.bwf.lgqingdan.utils.UrlHandler;
import com.bwf.lgqingdan.utils.http.lib.FormBody;
import com.bwf.lgqingdan.utils.http.lib.HttpUtils;
import com.bwf.lgqingdan.utils.http.lib.Request;
import com.bwf.lgqingdan.utils.http.lib.RequestBody;
import com.bwf.lgqingdan.utils.http.qingdan.HttpClient;

/**
 * Created by Administrator on 2016/11/15.
 */

public class CategoryThingModelImpl implements CategoryThingModel{
    private int categoryId;

    public CategoryThingModelImpl(int categoryId) {
        this.categoryId = categoryId;
    }

    @Override
    public void loadInitData(final Callback callback) {
        RequestBody body = new FormBody.Builder()
                .add(Apis.BODY_CATEGORY_DATA_NAME, UrlHandler.handlUrl(Apis.BODY_CATEGORY_DATAS_VALUE,categoryId))
                .build();
        Request.Builder builder = new Request.Builder()
                .url(Apis.API_CATEGORY_DATAS)
                .post(body);
        HttpClient.excute(builder, new HttpUtils.Callback() {
            @Override
            public void onResponse(String response) {
                ResponseCategoryThing responseCategoryThing = JSON.parseObject(response, ResponseCategoryThing.class);
                if(responseCategoryThing.getCode() == 0){
                    callback.loadInitDataSuccess(responseCategoryThing);
                }else{
                    callback.loadInitDataFailed(responseCategoryThing.getMessage());
                }
            }

            @Override
            public void onError() {
                callback.loadInitDataFailed("获取服务器数据失败");
            }
        });
    }

    @Override
    public void loadThingsData(String url, final Callback callback) {
        Request.Builder builder = new Request.Builder()
                .url(url)
                .get();
        HttpClient.excute(builder, new HttpUtils.Callback() {
            @Override
            public void onResponse(String response) {
                ResponseThings responseThings = JSON.parseObject(response,ResponseThings.class);
                if(responseThings.getCode() == 0){
                    callback.loadThingsDataSuccess(responseThings);
                }else{
                    callback.loadThingsDataFailed(responseThings.getMessage());
                }
            }

            @Override
            public void onError() {
                callback.loadThingsDataFailed("连接服务器失败");
            }
        });
    }
}
